﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Newton : MonoBehaviour {
	public static Newton Instance;

	public DrawLine drawLine;
	public float interval;
	private int n;
	private float length;
	private List<Vector2> p;
	private List<Vector2> pointList;
	private float[] a;

	private void Awake() {
		Instance = this;
	}

	// Start is called before the first frame update
	void Start() {
		n = RandomPointList.Instance.n;
		length = n * RandomPointList.Instance.interval;
		pointList = new List<Vector2>();
	}

	// Update is called once per frame
	void Update() {

	}

	public void NewtonAlgorithm() {
		p = RandomPointList.Instance.randomPointList;
		pointList.Clear();

		//计算系数a
		a = new float[n + 1];
		for (int j = 0; j <= n; j++) {
			a[j] = p[j].y;
		}
		for (int k = 1; k <= n; k++) {
			for (int j = n; j >= k; j--) {
				a[j] = (a[j] - a[j - 1]) / (p[j].x - p[j - k].x);
			}
		}
		//牛顿差值算法
		for (int j = 0; j * interval < length; j++) {
			float x = j * interval;
			float p = a[n];
			for (int i = n - 1; i >= 0; i--) {
				p = p * (x - this.p[i].x) + a[i];
			}
			pointList.Add(new Vector2(x, p));
		}
		//System.Threading.Thread.Sleep(10);
		drawLine.pointList = pointList;
		//drawLine.UpdateLine();
	}
}
